package com.ruoyi.system.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.Sales;
import com.ruoyi.system.service.ISalesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 销量Controller
 *
 * @author ruoyi
 * @date 2022-04-13
 */
@RestController
@RequestMapping("/system/sales")
public class SalesController extends BaseController {
    @Autowired
    private ISalesService salesService;

    /**
     * 查询销量列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Sales sales) {
        startPage();
        List<Sales> list = salesService.selectSalesList(sales);
        return getDataTable(list);
    }

    @GetMapping("/info")
    public AjaxResult info(){
        Sales sales = new Sales();
        List<Sales> list = salesService.selectInfo();
        List<Sales> collect = list.stream().sorted(Comparator.comparing(Sales::getValue).reversed()).limit(5).collect(Collectors.toList());
        return AjaxResult.success(collect);
    }

    /**
     * 获取销量详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(salesService.selectSalesById(id));
    }

    /**
     * 新增销量
     */
    @PostMapping
    public AjaxResult add(@RequestBody Sales sales) {
        Sales res = new Sales();
        res.setName(sales.getName());
        List<Sales> list = salesService.selectSalesList(res);
        Assert.isTrue(list.size()==0,"已有该乡镇销量");
        sales.setCreateUser(SecurityUtils.getUserId().intValue());
        return toAjax(salesService.insertSales(sales));
    }

    /**
     * 修改销量
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Sales sales) {
        sales.setUpdateUser(SecurityUtils.getUserId().intValue());
        return toAjax(salesService.updateSales(sales));
    }

    /**
     * 删除销量
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(salesService.deleteSalesByIds(ids));
    }
}
